$(document).ready(function() {
    $('#bLogin').click(function() {
        var username = $('#username').val();
        var password = $('#password').val();
        login(username, password);
    });
});

$(".password-field").keyup(function(event) {
    if (event.keyCode === 13) {
        $('#bLogin').click();
    }
});

function login(username, pw) {
    $.ajax({
        type: "POST",
        async: false,
        url: 'j_security_check',
        data: {
            j_username: username,
            j_password: pw
        },
        success: function() {
            initSession(username, pw);
        },
        error: function(err) {
            //$('#error').removeClass('hidden');
            //$('#errormessage').text(err.statusText);
            //$('#username').focus();
        }
    });
}

function initSession(username, password) {
    $.ajax({
        url: '../rest/users/' + username,
        type: 'GET',
        contentType: 'application/json; charset=UTF-8',
        dataType: 'json',
        async: false,
        success: function(data) {
            if($.cookie('kakvar') === undefined) {
                $.cookie('kakvar', 10, { expires: 365, path:'/' });
            }
            if (/\/login.html$/.test(window.location.pathname)) {
                window.location.href = '../sa/faq.html';
            } else {
                window.location.reload();
            }
        },
        error: function() {
            $('#error').removeClass('hidden');
            $('#errormessage').text("Fel vid hämtning av profil");
            $('#username').focus();
        }
    });
}
